<?php
declare(strict_types=1);

/**
 * 百度地图经纬度解析
 */
namespace Service\VendorClient\Qmap;
use Service\BaseService;
use Service\Code\Normal;
use Service\ExtraService\IdService;
use App\Service\TaskServer\TaskWorker;
class QmapApiClient extends BaseService
{
    protected $config;
    public function __construct(array $apiBody = [])
    {
        $this->config = $apiBody;
    }
    
    /**
     * 查询经纬度归属地址
     * @param $params
     * @return mixed
     */
    public function queryAddressByLatLng(string $lat,string $lng)
    {
        if( empty($this->config['baseurl']) ) {
            return Normal::returnCode(Normal::FAIL,"当前百度查询经纬度归属地址baseurl未配置");
        }
        
        $location   = $lat.','.$lng;
        $path       = '/ws/geocoder/v1';
        $param      = "location={$location}&key={$this->config['key']}";
        parse_str($param,$param_array);
        ksort($param_array);
        $newparam   = rawurldecode(http_build_query($param_array));
        $sign       = md5($path.'?'.$newparam.$this->config['secret']);
        $url        = $this->config['baseurl']."?key={$this->config['key']}&location={$location}&sig={$sign}";
        $parameter = [
            [
                'tag'       => 'qmap_latlngto_query',
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => [],
                'method'    => 'GET',
                'format'    => 'x-www-form-urlencoded',
                'header'    => [],
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result'];
        $resHttp = json_decode($res, true);
        $errorMsg = $resHttp['message'] ?? '当前百度查询经纬度归属地查询请求失败，请联系高德客服解决!';
        if (isset($resHttp['status']) && $resHttp['status'] == '0') {
            return Normal::returnCode(Normal::SUC, "操作成功",[
                'province'  => $resHttp['result']['address_component']['province'],
                'city'      => $resHttp['result']['address_component']['city'],
                'district'  => $resHttp['result']['address_component']['district'] ??'',
                'lat'       => $lat,
                'lng'       => $lng
            ]);
        }
        return Normal::returnCode(Normal::FAIL, $errorMsg);
    }
}